<?php
namespace common\services;

use common\models\UserMessage;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;

class UserMessageServices extends UserMessage
{

    /**
     * 用户消息查询
     * @param $params
     * @return array
     */
    public function search($params){
        $model = UserMessage::find(false);
        $model->orderBy('id desc');

        if (!empty($params['sender_id'])) {
            $model->andFilterWhere(['=', 'sender_id', $params['sender_id']]);
        }
        if (!empty($params['receiver_id'])) {
            $model->andFilterWhere(['=', 'receiver_id', $params['receiver_id']]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['is_read']) && $params['is_read'] != '') {
            $model->andFilterWhere(['=', 'is_read', $params['is_read']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or', ['like', 'content', $params['keywords']], ['like', 'sender_id', $params['keywords']], ['like', 'receiver_id', $params['keywords']]]);
        }

        return $dataProvider;
    }

    /**
     * 查询收到的消息
     * @param $receiverId
     * @return array
     */
    public function getMessageRemindByUserId($receiverId) {
        $model = UserMessage::find(false)->andFilterWhere(['=', 'status', UserMessage::STATUS_FLAG_NORMAL]);
        $model->andFilterWhere(['=', 'receiver_id', $receiverId])->select('id,sender_id,receiver_id,content,read_at,is_read,status,created_at');
        $res = $model->asArray()->orderBy('id desc')->all();
        $data = array(
            'all' => $res,
            'all_count' => count($res),
            'is_read' => 0,
            'not_read' => 0,
        );
        if (!empty($res)) {
            foreach ($res as $val) {
                if ($val['is_read']) {
                    $data['is_read'] ++;
                }else{
                    $data['not_read'] ++;
                }
            }
        }
        return $data;
    }

}
